package com.wbhz.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wbhz.entity.User;
import com.wbhz.service.PostService;
import com.wbhz.service.UserService;
import com.wbhz.util.MessageUtil;

@Controller
public class UserController {
	Logger logger = Logger.getLogger(UserController.class);
	
	@Autowired
	UserService userService=null;
	
	@Autowired
	PostService postService=null;
	
	// QA社区入口
	@RequestMapping("/")
	public String entry(){
		logger.info("===UserController类的,entry方法===");
		return "user/login";
	}
	// 注册
	@RequestMapping("/user/register")
	public String register(@ModelAttribute User user, HttpServletResponse response, HttpSession httpSession, Integer code) throws IOException{
		logger.info("===UserController类的,register方法===");
		Integer codeResult = (Integer) httpSession.getAttribute("result");// 获得验证码正确值，Image.jsp
		System.out.println(" ==test== code: ["+ code +"]"+"code: ["+ codeResult +"]");
		User obj = userService.selectUserByEmail(user);
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		if (code.equals(codeResult) && null==obj) {	// 用户名不能相同，即库中无相同用户名
			int count = userService.insertUser(user);
			if (count==1) {
				userService.insertRight(user);	// 赋予用户权限：插入权限表
				String random = RandomStringUtils.random(16, false, true); // 个数，数字，字符
		        System.out.println(" ==test== random: ["+ random +"]");
		        System.out.println(" ==test== userName: ["+ user.getUserName() +"]");
				userService.insertBankCard(user.getUserName(), random);	// 随机生成银行卡号码
				out.flush();
				out.println("<script>");
				out.println("alert('注册成功！即将转到登录页面！');");
				out.println("</script>");
				return "user/login";
			}
		}
		out.flush();
	    out.println("<script>");
	    out.println("alert('此用户名已存在，请重新输入！');");
	    out.println("history.back();");
	    out.println("</script>");
		return "user/reg";
	}
	// 登录
	@RequestMapping("/user/login")
	public String login(@ModelAttribute User user, HttpSession httpSession, HttpServletRequest request, Integer code) throws IOException{
		logger.info("===UserController类的,login方法===");
		Integer codeResult = (Integer) httpSession.getAttribute("result");// 获得验证码正确值，Image.jsp
		System.out.println(" ==test== code: ["+ code +"]"+"code: ["+ codeResult +"]");
		User obj = userService.selectUserByEmailAndPwd(user);
		if (code.equals(codeResult) && null != obj) {	// 检验验证码、用户名和密码
			logger.info("登录成功，进入首页。"); 
			System.out.println(" ==test== userName: ["+obj.getUserName()+"]");
			httpSession.setAttribute("User", obj);
			// 获得银行卡信息，在基本设置中，显示出用户的银行卡号码，银行卡余额给显示（可选项，银行卡余额默认足够多就可以不显示）
			httpSession.setAttribute("bankCard", userService.selectBankCard(obj.getUserId()));
			httpSession.setAttribute("right", userService.selectURight(obj.getUserId()));	// 获得权限
			return "index";
		}else {
			request.setAttribute(MessageUtil.LOGIN_MSG, MessageUtil.LOGIN_FAILED_MSG);
//			httpSession.setMaxInactiveInterval(1);   //设置该消息存在一秒，显示后下次访问页面即消失
			return "user/login";
		}
	}
	// 退出
	@RequestMapping("/logout")
	public String logout(HttpSession httpSession) {
		logger.info("===UserController类的,logout方法===");
		User user = (User) httpSession.getAttribute("User");  //从sesion中获取MsAdmin对象
		if(user != null) {
			httpSession.removeAttribute("User");  //移除
			return "user/login";   //重定向到登登录界面
		}
		return "user/login";
	}
	// 修改用户信息
	@RequestMapping("/user/updateUserDetail")
	public String updateUserDetail(@ModelAttribute User user, HttpServletResponse response, HttpSession httpSession) throws IOException {
		logger.info("===UserController类的,updateUserDetail方法===");
		int count = userService.updateUserDetail(user);
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		if (count == 1) {
			System.out.println("修改成功！");
			out.flush();
			out.println("<script>");
			out.println("alert('修改成功！');");
			out.println("</script>");
		}else {
			System.out.println("修改失败！");
			out.flush();
			out.println("<script>");
			out.println("alert('修改失败！');");
			out.println("history.back();");
			out.println("</script>");
		}
		// 从数据库中获得新数据
		User obj = userService.selectUserByEmail(user);
		httpSession.setAttribute("User", obj);
		return "forward:set.jsp";
	}
	// 修改密码
	@RequestMapping("/user/updatePwd")
	public String updatePwd(String oldPwd, String newPwd, String confirmPwd, HttpSession httpSession) {
		logger.info("===UserController类的,upadtePwd方法===");
		User user = (User) httpSession.getAttribute("User");
		System.out.println(user.getUserPwd());
		if (oldPwd.equals(user.getUserPwd()) && newPwd.equals(confirmPwd)) {	// 不能用==，要用.equals()
			int count = userService.updatePwd(newPwd, user.getUserEmail());
			if (count == 1) {
				System.out.println("修改密码成功！");
				httpSession.setAttribute(MessageUtil.LOGIN_MSG, MessageUtil.UPDATE_PWD_SUCCESS_MSG);
				httpSession.setMaxInactiveInterval(1);   //设置该消息存在一秒，显示后下次访问页面即消失
				return "user/login";
			}
		}
		System.out.println("修改密码失败！");
		httpSession.setAttribute(MessageUtil.UPDATE_PWD_MSG, MessageUtil.UPDATE_PWD_FAILED_MSG);
		httpSession.setMaxInactiveInterval(1);   //设置该消息存在一秒，显示后下次访问页面即消失
		return "user/set";
	}
	// 用户主页
	@RequestMapping("/showUserHome")
	public String showUserHome() {
		logger.info("===UserController类的,showUserHome方法===");
		return "user/home";
	}
	@RequestMapping("/user/showUserHome2")
	public String showUserHome2() {
		logger.info("===UserController类的,showUserHome2方法===");
		return "user/home";
	}
	// 消息
	@RequestMapping("/user/showMessage")
	public String showMessage(int userId, Model model) {
		logger.info("===UserController类的,showMessage方法===");
		model.addAttribute("msg", userService.selectUserMsg(userId));
//		System.out.println(userService.selectUserMsg(userId));
		return "user/message";
	}
	@RequestMapping("/user/showMsgDetail")
	public String showMsgDetail(int msgId, Model model) {
		logger.info("===UserController类的,showMsgDetail方法===");
		model.addAttribute("msgDetail", userService.selectMsgDetail(msgId));
		// 设置为已读
		return "user/messageDetail";
	}
	
	@RequestMapping("/user/toDeleteOneMsg")
	public String toDeleteOneMsg(int msgId) {
		logger.info("===UserController类的,toDeleteOneMsg方法===");
		
		return "user/message";
	}
	
	@RequestMapping("/user/toDeleteAllMsg")
	public String toDeleteAllMsg() {
		logger.info("===UserController类的,toDeleteAllMsg方法===");
		
		return "user/message";
	}
	
	@RequestMapping("/user/showIndexUser")
	public String showIndexUser(int userId, Model model) {
		logger.info("===UserController类的,showIndexUser方法===");
		model.addAttribute("userPost", postService.selectPostByUId(userId));
		model.addAttribute("userCollect", postService.selectUserCollect(userId));
		model.addAttribute("userCollectPost", postService.selectUserCollectPost(userId));
		return "user/indexUser";
	}
	// 会员vip
	@RequestMapping("/user/showVip")
	public String showVip(HttpServletRequest request, int userId) {
		logger.info("===UserController类的,showVip方法===");
		request.setAttribute("vipDetail", userService.selectVipDetail(userId));
		return "user/vip";
	}
	@RequestMapping("/user/refillBankCard")
	public String refillBankCard(String bankcardNumber, String bankcardPwd, String balance, HttpSession httpSession, HttpServletResponse response) throws IOException {
		logger.info("===UserController类的,refill方法===");
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (null != userService.selectB_CByNumAndPwd(bankcardNumber, bankcardPwd)) { // 银行卡号和密码输入无误
			userService.subB_Cbalance(bankcardNumber, Integer.parseInt(balance));	// 减少银行卡金额
			User user = (User)httpSession.getAttribute("User");
			postService.updateUserMoney(user.getUserId(), Integer.parseInt(balance) * 10);	// 增加飞吻值
		    out.println("<script>");
		    out.println("alert('充值成功！');");
		    out.println("</script>");
		}else {
		    out.println("<script>");
		    out.println("alert('充值失败！卡号或密码有误！');");
		    out.println("history.back();");
		    out.println("</script>");
		}
		return "user/vip";
	}
	// 购买vip
	@RequestMapping("/user/toPayVip")
	public String toPayVip(String balance, String payWay, int userId, HttpServletResponse response) throws IOException {
		logger.info("===UserController类的,toPayVip方法===");
		int balanceToInt = Integer.parseInt(balance);
		response.setContentType("text/html; charset=UTF-8"); //转码
		PrintWriter out = response.getWriter();
		out.flush();
		if (payWay.equals("1")) {	// 银行卡
			System.out.println("payWay1: ["+ payWay +"]");
			if (null != userService.isEnougBalance(userId, balanceToInt)) {	// 查询用户银行卡余额是否充足
				userService.subB_CBalance2(balanceToInt, userId);
				if (balanceToInt == 18) {
					userService.insertVipMonth(userId, 1);	// 插入VIP信息
				}else if (balanceToInt == 50) {
					userService.insertVipMonth(userId, 3);	// 插入VIP信息
				}else if (balanceToInt == 100) {
					userService.insertVipMonth(userId, 6);	// 插入VIP信息
				}else if (balanceToInt == 188) {
					userService.insertVipMonth(userId, 12);	// 插入VIP信息
				}
				userService.updateURight(userId);	// 修改用户权限为2(VIP)
				out.println("<script>");
				out.println("alert('购买成功！');");
				out.println("parent.location.reload()");	// 刷新父页面，即index.jsp，为了显示VIP图标
				out.println("</script>");
				return null;
			}
		}else if (payWay.equals("2")) {	// 飞吻
			System.out.println("payWay2: ["+ payWay +"]");
			if (null != userService.isEnougMoney(userId, balanceToInt)) {	// 查询用户飞吻余额是否充足
				if (balanceToInt == 18) {
					userService.subUMoney(userId, 249);	// 扣除飞吻数
					userService.insertVipMonth(userId, 1);	// 插入VIP信息
				}else if (balanceToInt == 50) {
					userService.subUMoney(userId, 680);
					userService.insertVipMonth(userId, 3);	// 插入VIP信息
				}else if (balanceToInt == 100) {
					userService.subUMoney(userId, 1200);
					userService.insertVipMonth(userId, 6);	// 插入VIP信息
				}else if (balanceToInt == 188) {
					userService.subUMoney(userId, 2000);
					userService.insertVipMonth(userId, 12);	// 插入VIP信息
				}
				userService.updateURight(userId); // 修改用户权限为2(VIP)
				out.println("<script>");
				out.println("alert('购买成功！');");
				out.println("parent.location.reload()");	// 刷新父页面，即index.jsp，为了显示VIP图标
				out.println("</script>");
				return null;
			}
		}
		out.println("<script>");
	    out.println("alert('购买失败：余额不足！');");
	    out.println("history.back();");
	    out.println("</script>");
		return "user/vip";
	}
}
